<template>
	<div class="replenishmentList">
		<div class="replenishmentList-left" :style="{height:windowHeight+'px'}">

			<div v-for="(item,index) in list" :key="index">
				<div class="van-sidebar-item" :class="[currentIndex==index?'select':'']" @click="clickIndex(index)">
					0{{index+1}}号柜门
					<div class="van-info" v-if="!item.amount && item.boxId">补</div>
				</div>
			</div>
		</div>
		<div class="replenishmentList-right">
			<div class="equipment-codes">
				<div class="equipment-name">设备编号</div>
				<input class="equipment-code" type="text" placeholder-class="inputPlaceHold"
					v-model.lazy="formData.code" placeholder="输入设备盒子编码" maxlength="16" @change="inputChange" id="code"
					:disabled="isCode" />
				<image class="install-icon" :src="localImages +'/yw-scan.png'" v-if="!isCode" @click="getScan(1)" />
			</div>
			<template v-if="currentItem.amount && !isChange">
				<div class="equipment-codes">
					<div class="equipment-name">商品编码</div>
					<div class="equipment-code">{{currentItem.skucode}}</div>
					<!-- <input class="equipment-code" type="number" placeholder-class="inputPlaceHold"
						v-model.lazy="currentItem.skucode" placeholder="请输入商品条码" maxlength="16" @change="inputChange"
						id="skucode" /> -->
					<image class="install-icon" :src="localImages +'/yw-scan.png'" v-show="isChange"
						@click="getScan(2)" />
				</div>
				<div class="equipment-codes">
					<div class="equipment-name" @click="isTest=!isTest">商品名称</div>
					<div class="equipment-code">{{currentItem.name}}</div>
				</div>
			</template>
			<template v-else>
				<div class="equipment-codes">
					<div class="equipment-name">商品编码</div>
					<input class="equipment-code" type="number" placeholder-class="inputPlaceHold"
						v-model.lazy="formData.skucode" placeholder="请输入商品条码" maxlength="16" @change="inputChange"
						id="skucode" />
					<image class="install-icon" :src="localImages +'/yw-scan.png'" v-show="" @click="getScan(2)" />
				</div>
				<div class="equipment-codes">
					<div class="equipment-name" @click="isTest=!isTest">商品名称</div>
					<div class="equipment-code">{{formData.name}}</div>
				</div>
				<div class="equipment-codes" v-if="formData.isModify && 0">
					<div class="equipment-name">补货日期</div>
					<div class="equipment-code oneline">{{date}}</div>
				</div>
			</template>
		</div>

		<div class="repWorkerOrder-total" v-if="1">
			<div>
				<span v-if="0">共补货{{totalNumber}}件</span>
			</div>
			<div class="repToWorker" v-if="currentItem.amount && !isChange" @click="changeStatus(currentIndex)"
				:class="[1 ?'':'isActive']">修改补货
			</div>
			<div class="repToWorker" v-else @click="openDoorLimit(currentIndex)"
				:class="[formData.name ?'':'isActive']">开门补货
			</div>
		</div>
	</div>
</template>

<script>
	import config from '../../static/config.js'
	import util from '../../static/utils/util.js'
	export default {
		data() {
			return {
				images: config.images,
				localImages: config.localImages,
				title: '123',
				showModal: 0,
				previous: '',
				secrect: '',
				//可使用窗口高度-底部菜单高度/rpx转px单位比例
				windowHeight: (wx.getSystemInfoSync().windowHeight - 101 / wx.getSystemInfoSync().pixelRatio),
				list: [{
					amount: 0,
					id: 0
				}, {
					amount: 1,
					id: 1
				}],
				list: 7,
				currentIndex: 0,
				currentItem: {
					name: '',
					skucode: '',
					amount: 0,
				},
				formData: {
					name: '',
					code: '',
					skucode: '',
					isModify: false,
				},
				isCode: false, //已经扫描到正确的设备编号的标记
				date: '',
				isChange: false, //修改补货标记
				isTest: false, //开启测试，直接换货，绕开蓝牙判断和开门
			}
		},
		onLoad() {
			//只打开蓝牙，不连接设备
			this.initBLEApp(false)
		},
		async onShow() {
			var isConnect = getApp().globalData.isConnect
			//有更新补货商品才去重新连接设备
			if (!isConnect) {
				if (this.formData.isModify) {
					this.initBLEApp()
				} else {}

			} else {
				//此处不需要重新连接，开门会去重连
				//更新下设备连接状态
				// var isConnect = await getApp().testConnectStatus()
				// console.log('show-isConnect', isConnect)
			}
		},
		onUnload() {
			this.clearName()
		},
		methods: {
			//清空设备信息
			clearName() {
				console.log('this.name', this.name)
				getApp().globalData.battery = 0
				getApp().globalData.deviceId = ""
				getApp().globalData.isConnect = false
				getApp().globalData.name = ""
			},
			async initBLEApp(flag = true) {
				var res = await getApp().initBLE(flag)
				console.log('initBLEApp-res', res)
			},
			async inputChange(e) {
				// console.log(e)
				var value = e.detail.value;
				var key = e.currentTarget.id;
				if (!value.length) return
				if (key == 'code') {
					this.queryGoods(value)
				}
				if (key == 'skucode') {
					this.addGoods(value)
				}
			},
			clickIndex(index) {
				//切换条目，重置表单数据
				this.resetFormData()
				this.currentIndex = index
				this.currentItem = this.list[index]
			},
			//重置表单数据
			resetFormData() {
				var {
					code,
					name
				} = this.formData
				// console.log('code', code)
				//this.$options.data() 获取该组件初始状态下的data
				var formData = this.$options.data().formData
				// 不重置code值
				this.formData = {
					...formData,
					code,
				}
				this.isChange = false
			},
			getScan(type = 0) {
				var self = this
				wx.scanCode({
					success(res) {
						var result = res.result
						console.log('result', result)
						if (type == 1) {
							var code = result.substr(result.lastIndexOf('/') + 1)
							console.log('code', code)
							self.queryGoods(code)
						}
						if (type == 2) {
							if (!!result.match(/^\d+$/)) {
								// self.queryGoodsByCode(result)
								self.addGoods(result)
							} else {
								wx.showToast({
									title: '商品码有误！',
									icon: 'none',
								})
							}
							console.log('code', code)
						}
					},
					fail(res) {
						console.log('scanCode=fail', res)
					}
				})
			},
			// 补货员 获取商品列表 initBLE是否连接蓝牙
			async queryGoods(code, connectBLE = true) {
				var url = '/agent/boxadmin/queryGoods'
				// var code="4280046158"
				var params = {
					code
				}
				var options = {
					url,
					params
				}
				try {
					var param = await util.requestPro(options)
					this.list = param.result
					this.formData.code = code
					this.isCode = true
					this.clickIndex(this.currentIndex)
					getApp().globalData.name = code
					//连接蓝牙
					if (connectBLE) {
						this.initBLEApp()
					}
					console.log('queryGoods', param)
				} catch (e) {
					console.log('queryGoods-catch', e)
					//重置数据
					this.list = 7
					this.formData.code = ''
					this.clearName()
					this.currentItem = this.$options.data().currentItem
				}

			},

			//添加补货
			async addGoods(code) {
				var goodsInfo = await this.queryGoodsByCode(code)
				this.formData.name = goodsInfo.name
				this.formData.skucode = goodsInfo.skucode
				this.formData.isModify = true
				var date = util.formatYearDayTime()
				this.date = date
			},
			//按钮开启修改补货
			changeStatus(currentIndex) {
				var item = this.list[currentIndex]
				var {
					name,
					skucode
				} = item
				this.isChange = true
				this.formData.name = name
				this.formData.skucode = skucode
				this.formData.isModify = true
			},

			// 补货员 根据商品码查商品
			async queryGoodsByCode(code) {
				var url = '/agent/boxadmin/queryGoodsByCode'
				// var code="4280046158"
				var params = {
					code
				}
				var options = {
					url,
					params
				}
				try {
					var param = await util.requestPro(options)
					var goodsInfo = param.result
					console.log('goodsInfo=', goodsInfo)
					return goodsInfo
				} catch (e) {
					console.log('queryGoodsByCode-catch', e)
					//清空商品名称
					this.formData.name = ''
				}
			},

			//函数限流2s
			openDoorLimit(index) {
				util.tottleOne(() => {
					this.openDoor(index)
				})
			},
			//开门逻辑
			async openDoor(index) {
				if (!this.formData.code) {
					wx.showToast({
						title: '设备编码不能为空！',
						icon: 'none',
					})
					return
				}
				//延迟时间保护，等查询完商品码接口后，拿到最新的状态，判断商品码是否有误
				setTimeout(async () => {
					if (!this.formData.name) {
						wx.showToast({
							title: '商品码有误！',
							icon: 'none',
						})
						return
					}
					//蓝牙连接判断
					// var isConnect = getApp().globalData.isConnect
					// if (!isConnect) {
					// 	util.toast('蓝牙未连接')
					// 	return
					// }
					//展示加载中
					wx.showLoading({
						title: '',
						duration: 1000
					})
					if (this.isTest) {
						this.onShowModal()
					} else {
						this.openDoorDetail()
					}
				}, 500)
			},

			// 开门的逻辑
			async openDoorDetail() {
				//3下单前再次连接设备，确保支付后可以开门
				var isConnect = await getApp().testConnectStatus()
				console.log('isConnect=', isConnect)
				if (!isConnect) {
					return
				}
				wx.showLoading({
					title: '开门中',
					duration: 2000
				})
				//开门
				var door = this.currentIndex + 1
				var openDoorFlag = await getApp().testOpenDoor(door)
				//开门成功，然后刷新下商品列表
				console.log('openDoorFlag=', openDoorFlag)
				if (openDoorFlag) {
					this.onShowModal()
				}
			},

			saveGoods() {
				//延迟时间保护，等查询完商品码接口后，拿到最新的状态，判断商品码是否有误
				setTimeout(() => {
					if (!this.formData.isModify) {
						wx.showToast({
							title: '商品码有误！',
							icon: 'none',
						})
						return
					}
				}, 500)

				this.onShowModal()

			},
			async onShowModal() {
				var self = this;
				wx.showModal({
					title: '用户提示',
					content: '补货商品确认:' + this.formData.name,
					cancelColor: "#999999",
					confirmColor: "#1086FF",
					confirmText: '确认',
					cancelText: '取消',
					async success(res) {
						if (res.confirm) {
							await self.supply();
							//刷新下列表,不要重新连接蓝牙
							self.queryGoods(self.formData.code,false)
						} else if (res.cancel) {

						}
					}
				})
			},
			// 补货员 确认补货
			async supply(code) {
				var url = '/agent/boxadmin/supply'
				var {
					code,
					skucode
				} = this.formData
				var {
					doorNo
				} = this.currentItem
				var params = {
					boxCode: code,
					doorNo: doorNo,
					goodsCode: skucode,
				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
				util.toast('补货成功')
			},

		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.replenishmentList {
		display: flex;
	}

	.replenishmentList-left {
		width: 292rpx;
		background: #6d92ff;
		box-shadow: 8rpx 0 10rpx 0 rgb(109 146 255 / 30%);
		border-radius: 0 50rpx 50rpx 0;
		overflow-y: auto;
		padding: 20rpx 0 0 20rpx;
	}

	.van-sidebar-item {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #6d92ff;
		color: #fff;
		padding: 0;
		height: 92rpx;
		margin-top: 30rpx;
		margin-bottom: 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #f2f2f2;
	}

	.van-info {
		position: absolute;
		right: 4rpx;
		top: 4rpx;
		min-width: 32rpx;
		padding: 0 6rpx 0 6rpx;
		color: #fff;
		background: #ee0a24;
		font-size: 26rpx;
		border-radius: 16rpx;
	}

	.van-sidebar-item.select {
		background-color: #fff;
		color: #333;
		border-color: transparent;
		border-radius: 30rpx 0 0 30rpx;
	}

	.van-sidebar-item.select::before {
		position: absolute;
		top: 50%;
		left: 0;
		width: 6rpx;
		height: 20rpx;
		background-color: #ee0a24;
		transform: translateY(-50%);
		content: "";
	}

	.replenishmentList-right {
		width: 100%;
		height: fit-content;
		box-shadow: 0px 10rpx 10rpx 0px rgba(114, 96, 255, 0.1);
		overflow-y: auto;
		margin: 20rpx 0 0 20rpx;
		padding: 20rpx 40rpx 20rpx 20rpx;
		border-radius: 30rpx 0 0 30rpx;
		background: #fff;
	}

	.equipment-codes {
		display: flex;
		padding: 30rpx 0rpx 30rpx 0rpx;
		align-items: center;
		line-height: 44rpx;
		border-bottom: 1rpx solid rgba(240, 240, 240, 1);
	}

	.equipment-name {
		height: 44rpx;
		width: 120rpx;
		font-size: 30rpx;
		white-space: nowrap;
		/* border: 1rpx solid #f00; */
	}

	.equipment-code {
		width: 260rpx;
		margin-left: 20rpx;
		/* border: 1rpx solid #0f0; */
	}

	.equipment-code.oneline {
		white-space: nowrap;
	}

	.install-icon {
		display: inline-block;
		width: 38rpx;
		height: 38rpx;
		vertical-align: middle;
		margin-left: 20rpx;
		/* border: 1rpx solid #00f; */
	}

	.repWorkerOrder-total {
		position: fixed;
		bottom: 0;
		left: 0;
		height: 100rpx;
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #fff;
		box-shadow: 0 -6px 4px -4px rgba(0, 85, 255, 0.1);
		font-size: 30rpx;
		z-index: 99;
	}

	.repWorkerOrder-total>div:nth-child(1) {
		margin-left: 50rpx;
	}

	.repToWorker {
		display: flex;
		align-items: center;
		height: 100%;
		background: #6d92ff;
		color: #fff;
		margin-left: auto;
		padding: 0rpx 50rpx;
	}

	.repToWorker.isActive {
		background-color: #979eb2 !important;
		color: #5c616d !important;
	}
</style>
